package com.ice.ubt.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.util.Log;

import com.ice.ubt.event.UBTDataBean;
import com.ice.ubt.event.UBTEvent;
import com.ice.ubt.event.UBTEventDao;
import com.ice.ubt.greendao.DbCore;
import com.ice.ubt.net.API;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 
 * 上传统计数据
 * 
 *
 */
public class UploadDataService extends Service {
	private UBTEventDao ubtEventDao;
	private int uploadNum=50;
	@Override
	public void onCreate() {
		super.onCreate();
		Log.v("statistics","Service->onCreate");
		ubtEventDao = DbCore.getDaoSession().getUBTEventDao();

	}



	@Override
	public IBinder onBind(Intent intent) {
		Log.v("statistics","Service->onBind");
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		isUpload();
		return super.onStartCommand(intent, flags, startId);


	}

	@Override
	public ComponentName startService(Intent service) {
		Log.v("statistics","Service->startService");
		return super.startService(service);
	}

	@Override
	public void onDestroy() {
		Log.v("statistics","Service->onDestroy");
		super.onDestroy();
	}

	private boolean isUpload(){
		/*** start 查询数据库确定需要上传的数据 **/
		//List<String> list = EventDao.getInstance(this).queryEventList(5);
		List<UBTEvent> list =ubtEventDao.queryBuilder().list();
		/*** end 查询数据库确定需要上传的数据 **/

		if(list != null && list.size() >0){
			upload(list);
			return true;
		}else{
			//if(StatisticsHelper.isDebug){
			//	Log.v("statistics","uploadEventThread-->  上传线程的查询结果为空");
			//}
			return false;
		}
	}

	private void upload(final List<UBTEvent> list){
	/*	if(StatisticsHelper.isDebug){
			Log.v("statistics","uploadEventThread-->  查询的数据长度" + list.size());
			Log.v("statistics","uploadEventThread-->  查询结果：" + JsonUtil.getInstances().beanToJson(list));
			Log.v("statistics","uploadEventThread-->  Map参数结果：" + JsonUtil.getInstances().beanToJson(list.get(0).getEvent_param()));
		}*/
	//upload

		UBTDataBean dataBean = new UBTDataBean();
		// TODO: 17/6/15 取数据
		dataBean.data =list;
		dataBean.app = "UBT";
		dataBean.extra = "{}";
		dataBean.gps = "{}";
		dataBean.mobile = "13812345678";
		dataBean.token = "";
		API.getUBTServices().postUBTData(dataBean).enqueue(new Callback<Void>() {
			@Override
			public void onResponse(Call<Void> call, Response<Void> response) {
				// TODO: 17/6/14  清空已上传的数据
				Log.e("TAG", "onResponse:.... " + "sucess");
				ubtEventDao.deleteInTx(list);
				stopSelf();
			}

			@Override
			public void onFailure(Call<Void> call, Throwable t) {
				Log.e("TAG", "onFailure: " + t);
			}
		});
		/*try{
			Thread.sleep(500);
		}catch(InterruptedException e){
			System.out.println("线程异常...");
		}*/


		//EventDao.getInstance(this).deleteData(5);
		//isUpload();
	}

}
